package cn.passlink.www.Utils;

import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;
@Slf4j
public class RandomUtils {
    private static final String charlist = "abcdefghijklmnopqrst1234567890";
    //    根据提供的字符创建新字符
    public static String createRandomString(int len) {
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < len; i++) {
            str.append(charlist.charAt(getRandom(charlist.length())));
        }
        return str.toString();
    }

    public static int getRandom(int mod) {
        if (mod < 1) {
            return 0;
        }
        return getInt() % mod;
    }

    private static int getInt() {
        return Math.abs(Long.valueOf(getRandomNumString()).intValue());
    }

    private static String getRandomNumString() {
        double d = Math.random();
        String dStr = String.valueOf(d).replaceAll("[^\\d]", "");
        if (dStr.length() > 1) {
            dStr = dStr.substring(0, dStr.length() - 1);
        }
        return dStr;
    }

    /**
     * generateUniqueId
     *生产id
     * @return java.lang.String
     * @author passlink
     * @create 2023/10/14
     **/
    public static String generateUniqueId() throws NoSuchAlgorithmException {
        long timestamp = new Date().getTime();
        String stringToHash = Long.toString(timestamp);
        MessageDigest messageDigest = MessageDigest.getInstance("MD5");
        byte[] hashBytes = messageDigest.digest(stringToHash.getBytes());
        StringBuilder stringBuilder = new StringBuilder();
        for (byte b : hashBytes) {
            stringBuilder.append(String.format("%02x", b));
        }
        return stringBuilder.substring(0, 16);
    }
}